import { defineStore } from 'pinia';

// Error record interface
export interface ErrorRecord {
  id: string;
  timestamp: number;
  type: string;
  message: string;
  stack?: string;
  info?: any;
  source: 'main' | 'node' | 'renderer' | 'automation' | 'preload';
  read?: boolean;
}

export const useErrorStore = defineStore('error', {
  state: () => ({
    errors: [] as ErrorRecord[],
    unreadCount: 0,
    isInitialized: false,
  }),

  getters: {
    hasUnreadErrors: (state) => state.unreadCount > 0,
    latestError: (state) => state.errors.length > 0 ? state.errors[0] : null,
    allErrors: (state) => state.errors,
  },

  actions: {
    async initialize() {
      if (this.isInitialized) return;

      try {
        // 从主进程获取已有错误
        const storedErrors = await window.errorHandler.getAllErrors();
        if (storedErrors && Array.isArray(storedErrors)) {
          this.errors = storedErrors.map(err => ({ ...err, read: true }));
        }

        // 监听新错误
        window.errorHandler.onNewError((error) => {
          this.addError(error);
        });

        this.isInitialized = true;
      } catch (error) {
        console.error('Error initializing error store:', error);
      }
    },

    addError(error: ErrorRecord) {
      // 检查错误是否已存在（防止重复）
      const existingIndex = this.errors.findIndex(e => e.id === error.id);

      if (existingIndex === -1) {
        // 新错误添加到队列开头
        this.errors.unshift({
          ...error,
          read: false
        });

        // 限制错误数量，保留最近的100条
        if (this.errors.length > 100) {
          this.errors.pop();
        }

        // 更新未读计数
        this.unreadCount++;
      }
    },

    markAllAsRead() {
      this.errors = this.errors.map(error => ({ ...error, read: true }));
      this.unreadCount = 0;
    },

    markAsRead(errorId: string) {
      const index = this.errors.findIndex(e => e.id === errorId);
      if (index !== -1 && !this.errors[index].read) {
        this.errors[index].read = true;
        this.unreadCount = Math.max(0, this.unreadCount - 1);
      }
    },

    async clearErrors() {
      try {
        await window.errorHandler.clearErrors();
        this.errors = [];
        this.unreadCount = 0;
      } catch (error) {
        console.error('Error clearing errors:', error);
      }
    },

    // 手动上报错误
    async reportError(error: Omit<ErrorRecord, 'id' | 'timestamp' | 'read'>) {
      try {
        await window.errorHandler.reportError(error);
      } catch (err) {
        console.error('Error reporting error:', err);
      }
    }
  },
});
